package br.edu.utfpr.servlet;

import br.edu.utfpr.model.Usuario;
import br.edu.utfpr.dao.DaoUsuario;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author André Luis Schwerz
 */
@WebServlet(name = "UsuarioServlet", urlPatterns = {"/UsuarioServlet"})
public class UsuarioServlet extends HttpServlet {

    private String op;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        op = request.getParameter("op");
        if (op.equals("logoff")) {
            HttpSession session = request.getSession();
            session.removeAttribute("usuario");
            response.sendRedirect("index.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        op = request.getParameter("op");
        if (op.equals("logar")) {
            HttpSession session = request.getSession();
            DaoUsuario dao = new DaoUsuario();
            String login = request.getParameter("login");
            String senha = request.getParameter("senha");
            Usuario usuario = dao.logar(login, senha);
            if (usuario != null) {
                session.setAttribute("usuario", usuario);
                response.sendRedirect("home.jsp");
            } else {
                session.setAttribute("msg", "Login ou senha inválido!");
                response.sendRedirect("index.jsp");
            }

        }
    }
}
